﻿using HBKY.Shop.Common.PollyHelper.PollyAttribute;
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http.Headers;


namespace HBKY.Shop.Common.PollyHelper
{
    /// <summary>
    /// 模拟Http请求
    /// </summary>
    public class RequestApi
    {
        [CustomPollyRetry(Order = 2)]
        [CustomPollyTimeOut(Order = 1)]
        //[CustomPollyFallback]
        public virtual T Get<T>(HttpClient httpClient, string url, string param = null)
        {
            T result = default(T);
            httpClient.DefaultRequestHeaders.Accept.Clear();
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            StringBuilder requestUri = new StringBuilder(url);
            var response = httpClient.GetAsync(requestUri.ToString()).Result;
            if (response.IsSuccessStatusCode)
            {
                var res = response.Content.ReadAsStringAsync().Result;
                result = JsonConvert.DeserializeObject<T>(res);
            }
            else
            {
                throw new Exception(JsonConvert.SerializeObject(response.RequestMessage));
            }
            return result;
        }

        [CustomPollyRetry(Order = 2)]
        [CustomPollyTimeOut(Order = 1)]
        public virtual T Post<T>(HttpClient httpClient, string url, object param)
        {
            T result = default(T);
            var content = JsonConvert.SerializeObject(param);
            HttpContent httpContent = new StringContent(content);
            httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            var response = httpClient.PostAsync(url, httpContent).Result;
            if (response.IsSuccessStatusCode)
            {
                var res =  response.Content.ReadAsStringAsync().Result;
                result = JsonConvert.DeserializeObject<T>(res);
            }
            else
            {
                throw new Exception(JsonConvert.SerializeObject(response.RequestMessage));
            }
            return result;
        }
    }
}
